#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include "ohos_init.h"
#include "cmsis_os2.h"

#include "hi_errno.h"
#include "hi_adc.h"
#include "hi_io.h"
#include "hi_gpio.h"

/***** 获取电压值函数 *****/
static float Get_voltage(void)
{
    unsigned int ret;
    unsigned short data;
    // adc读取
    ret = hi_adc_read(HI_ADC_CHANNEL_5, &data, HI_ADC_EQU_MODEL_8, HI_ADC_CUR_BAIS_DEFAULT, 0xFF);
    if (ret != HI_ERR_SUCCESS)
    {
        printf("ADC Read Fail\n");
    }
    //将adc返回值转换电压的函数
    return (float)hi_adc_convert_to_voltage(data);
}

static void ADC_Task(void)
{
    float voltage;
    //初始化
    hi_gpio_init();

    //上拉，让按键未按下时GPIO_11保持高电平状态
    hi_io_set_pull(HI_GPIO_IDX_11, HI_IO_PULL_UP);

    while (1)
    {
        //获取电压值
        voltage = Get_voltage();
        //打印电压值
        printf("vlt:%.3fV\n", voltage);
        //延时1s
        usleep(1000000);
    }
}

static void ADC_demo(void)
{
    osThreadAttr_t attr;

    attr.name = "ADC_Task";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 1024 * 5;
    attr.priority = 24;

    if (osThreadNew((osThreadFunc_t)ADC_Task, NULL, &attr) == NULL)
    {
        printf("[ADCExample] Falied to create ADC_Task!\n");
    }
}

APP_FEATURE_INIT(ADC_demo);